<template>
    <div class="add-card">
      <header class="add-header">
        <el-page-header :content="id?'编辑月卡':'增加月卡'" @back="$router.back()" />
      </header>
      <main class="add-main">
        <div class="form-container">
          <div class="title">车辆信息</div>
          <div class="form">
            <el-form ref="carInfoRef" label-width="100px" :rules="carInfoRules"  :model="carInfo">
              <el-form-item label="车主姓名" prop="personName" >
                <el-input v-model="carInfo.personName"/>
              </el-form-item>
              <el-form-item label="联系方式" prop="phoneNumber">
                <el-input  v-model="carInfo.phoneNumber"/>
              </el-form-item>
              <el-form-item label="车辆号码" prop="carNumber">
                <el-input v-model="carInfo.carNumber"/>
              </el-form-item>
              <el-form-item label="车辆品牌" prop="carBrand">
                <el-input v-model="carInfo.carBrand"/>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="form-container">
          <div class="title">最新一次月卡缴费信息</div>
          <div class="form">
            <el-form ref="feeInfoRef" :rules="feeInfoRules" :model="feeInfo" label-width="100px">
            <el-form-item prop="payTime" label="有效日期">
              <!-- [ '2025-06-5', '2025-06-7' ] -->
              <el-date-picker v-model="feeInfo.payTime" value-format="YYYY-MM-DD" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" />
              </el-form-item>
              <el-form-item label="支付金额" prop="paymentAmount">
                <el-input   v-model="feeInfo.paymentAmount"  placeholder="请输入金额" />
              </el-form-item>
              <el-form-item label="支付方式" prop="paymentMethod">
                <el-select v-model='feeInfo.paymentMethod'>
                  <el-option v-for="item in payMethod" :key="item.label" :value="item.value" :label="item.label" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
  
      </main>
      <footer class="add-footer">
        <div class="btn-container">
          <el-button @click="cancel">重置</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </footer>
    </div>
  </template>
  
  <script lang="ts" setup>
import { addCardAPI, editCardAPI, getCardDetailAPI } from '@/apis/card';
import router from '@/router';
import type { AddCardParams } from '@/types/card';
import { validateCarNumber } from '@/utils/validate';
import { ElMessage, type FormInstance } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

  // 1. 添加月卡
// 车辆信息表单
    const carInfo  = ref<AddCardParams>({
  personName: '', // 车主姓名
  phoneNumber: '', // 联系方式
  carNumber: '', // 车牌号码
  carBrand: '' // 车辆品牌
})
// 支付信息
const feeInfo=ref({
    paymentAmount:'',//支付金额
    paymentMethod:'',//支付方式
    payTime:['',''],//支付时间
    rechargeId:-1,//缴费信息id
})
// 支付方式
const payMethod=[
    {
        label:'微信支付',
        value:'WeChat'
    },
    {
    label:'支付宝',
    value:'Alipay'
    },
    {
        label:'线下',
        value:'Cash'
    }
]
const carInfoRules ={
    // 车主姓名
    personName: [
      { required: true, message: '请输入车主姓名', trigger: 'blur' },
      { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    // 联系方式
    phoneNumber: [
      { required: true, message: '请输入联系方式', trigger: 'blur' },
      { min: 11, max: 11, message: '长度为11个字符', trigger: 'blur' }
    ],
    // 车牌号码
    carBrand: [
        { required: true, message: '请输入车牌品牌', trigger: 'blur' },
        { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
    ],
    carNumber: [
    { required: true, message: '请输入车辆号码', trigger: 'blur' },
    // 自定义校验
    { validator: validateCarNumber, trigger: 'blur'  }
  ],
}
// 缴费信息校验规则
const feeInfoRules = {
  paymentAmount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' },
    // 严谨来讲 只能是数字 \d 添加正则表达式 
    { pattern: /^[1-9]\d*$/, message: '请输入正确的支付金额', trigger: 'blur' }
  ],
  paymentMethod: [ 
    { required: true, message: '请选择支付方式', trigger: 'blur' }
  ],
  payTime: [
    { required: true, message: '请选择支付时间', trigger: 'blur' }
  ]
}
const carInfoRef = ref<FormInstance>()
const feeInfoRef = ref<FormInstance>()

// 获取月卡ID
const route = useRoute()
const id=computed(()=>{
  return route.query.id as string
})
onMounted(()=>{
  if(id.value){
    // 编辑月卡
    getCardDetail()
  }
})
const getCardDetail=async()=>{
  // 发送请求
  const res = await getCardDetailAPI(id.value)
  console.log(res.data)


  // 回显车辆信息
  const { carInfoId,  carBrand, personName, phoneNumber, carNumber } = res.data 
  carInfo.value = {
    carBrand,
    personName,
    phoneNumber,
    carNumber,
    carInfoId  // 车辆id -> 为了编辑月卡时使用
  }
  // 回显缴费信息
  const { rechargeId,  paymentAmount, paymentMethod, cardStartDate, cardEndDate } = res.data
  feeInfo.value = {
    paymentAmount: paymentAmount!,
    payTime: [cardStartDate!, cardEndDate!],
    paymentMethod: paymentMethod!,
    rechargeId: rechargeId! // 充值id
  }
  console.log('回车信息'+carInfo);
  console.log('回显信息2'+feeInfo);

}
// 确定提交
const confirm = async() => {
  // 分别针对于表单进行整体的校验
  await carInfoRef.value!.validate()
  await feeInfoRef.value!.validate()
  console.log('通过校验')
  const addPayload={
    ...carInfo.value,//
    paymentAmount:feeInfo.value.paymentAmount,
    paymentMethod:feeInfo.value.paymentMethod,
    cardStartDate:feeInfo.value.payTime[0],
    cardEndDate:feeInfo.value.payTime[1],
    // rechargeId:feeInfo.value.rechargeId
  }as  AddCardParams
//   提交请求
// await addCardAPI(addPayload)
//   重置表单
if(id.value){
  // 编辑月卡
  addPayload.rechargeId=feeInfo.value.rechargeId
  await editCardAPI(addPayload)
  ElMessage.success('编辑成功')
}else{
  await addCardAPI(addPayload)
  ElMessage.success('添加成功')

}

// 返回上一页
router.back()
}
// 重置
const cancel = async () => {
  await carInfoRef.value!.resetFields()
  await feeInfoRef.value!.resetFields()
}
  </script>
  
  <style scoped lang="scss">
  .add-card {
    background-color: #f4f6f8;
    height: 100vh;
  
    .add-header {
      display: flex;
      align-items: center;
      padding: 0 20px;
      height: 64px;
      background-color: #fff;
  
      .left {
        span {
          margin-right: 4px;
        }
  
        .arrow {
          cursor: pointer;
        }
      }
  
      .right {
        text-align: right;
      }
    }
  
    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;
  
      .form-container {
        background-color: #fff;
  
        .title {
          height: 60px;
          line-height: 60px;
          padding-left: 20px;
        }
  
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
  
          .el-form {
            display: flex;
            flex-wrap: wrap;
  
            .el-form-item {
              width: 50%;
            }
          }
        }
      }
  
      .preview {
        img {
          width: 100px;
        }
      }
    }
  
    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>